<?php

namespace fztadmin\modules\user\models\forms;

use common\models\db\User;
use yii\base\Model;

class UpdatePasswrod extends Model
{
    public $oldPassword;
    public $password;
    public $rePassword;

    public function attributeLabels()
    {
        return [
            'oldPassword' => "老密码",
            'password' => "新密码",
            'rePassword' => "新密码确认",
        ];
    }

    public function rules()
    {
        return [
            [['password', 'rePassword'], 'required'],
            ['oldPassword', 'checkOldPassword'],
            ['password', 'string', 'min' => 6],
            ['rePassword', 'compare', 'compareAttribute' => 'password'],
        ];
    }

    /**
     * @param $attribute
     * @param $params
     */
    public function checkOldPassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '老密码错误');
            }
        }
    }

    public function updatePassword()
    {
        /**
         * @var User $user
         */
        $user = \Yii::$app->user->identity;
        $user->setPassword($this->password);
        if (!$user->save()){
            return false;
        }
        return true;
    }
}